'use strict'
const jwt = require('jsonwebtoken')
const config = require('../config')
const randomName = require('../lib/util.random.name')
const userServices = require('../services').user
const {InvalidQueryError, UsernameRepeatError, NoSuchUserError, RefuseRegisterError, ContentError} = require('../lib/error')
const bcrypt = require('bcryptjs');
const localTime = require('../lib/localTime');
const login = {}
const saltRounds = 10
const encryptPwd = (pwd) => {
    return new Promise(resolve => {
        bcrypt.hash(pwd, saltRounds).then(function (hash) {
            // Store hash in your password DB.
            resolve(hash)
        });
    })
}

login.login = async (ctx, next) => {
    console.log('login', ctx.request)
    console.log(ctx.request.body)
    const {userName, password} = ctx.request.body
    if (!userName || !password) {
        throw new InvalidQueryError()
    }

    const user = await userServices.login({
        userName: userName
    })

    if (!user) {
        throw new NoSuchUserError()
    } else {
        // await comparePwd(password,user.password)
        let match = await bcrypt.compare(password, user.password)
        if (!match) {
            throw new NoSuchUserError()
        }
        let token = jwt.sign({
            userId: user._id,
            userRole: user.userRole,
            // 设置 token 过期时间
            exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 7), // 60 seconds * 60 minutes = 1 hour
        }, config.secret)
        user.password = null
        console.log('user delete', user)
        ctx.result = {token, user: user}
    }
    return next()
}

login.register = async (ctx, next) => {
    if (!config.allowRegister) {
        throw new RefuseRegisterError()
    }
    const {userName, password} = ctx.request.body
    if (!userName || !password) {
        throw new InvalidQueryError()
    }
    if (userName.length > 12) {
        throw new ContentError('用户名不能超过12个字符')
    }
    let uPattern = /^[a-zA-Z0-9_-]$/;
    if (!uPattern.test(userName)) {
        throw new ContentError('用户名包含非法字符串')
    }
    // 校验用户名重复
    const number = await userServices.usernameRepeat({
        userName: userName,
    })
    if (number > 0) {
        throw new UsernameRepeatError()
    }

    const user = await userServices.register({
        userName: userName,
        password: await encryptPwd(password),
        nickName: randomName.get(),
        createTime: localTime()
    })
    ctx.result = jwt.sign({
        data: user._id,
        // 设置 token 过期时间
        exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 7), // 60 seconds * 60 minutes = 1 hour
    }, config.secret)
    return next()
}

login.usernameRepeat = async (ctx, next) => {
    const {userName} = ctx.request.body
    if (!userName) {
        throw new InvalidQueryError()
    }
    const number = await userServices.usernameRepeat({
        userName: userName,
    })
    ctx.result = !!number
    return next()
}

module.exports = login
